<?php
/**
 * 发送短信
 * @Author: lf
 * @Date:   2018-07-03T17:11:00+0800
 */
namespace app\admin\controller;

use app\admin\model\Channel;
use app\admin\model\Channelkey;
use app\services\MqInsertService;
use think\Db;
use think\facade\Env;

class SendNote extends Father
{

    public function index()
    {
        $this->assign('cha', Channel::field('channel_id,company_name')->all());
        $this->assign('thistime', date('Y-m-d H:i:s', time()));

        //需求：自定义注意事项
        $this->assign('send_attentiontxt', cache('send_attentiontxt')); //用于展示
        if (cache('send_attentiontxt')) {
            $this->assign('send_attentiontxt_e', addslashes(implode("\r\n", cache('send_attentiontxt')))); //用于编辑
        } else {
            $this->assign('send_attentiontxt_e', ''); //用于编辑
        }

        return $this->fetch();
    }

    /**
     * 发送短信
     * @Author   lf
     * @DateTime 2018-07-18T09:42:21+0800
     * @return   [type]                   [description]
     */
    public function send_n()
    {
        // session('username')
        set_time_limit(300);
        ini_set('memory_limit', '125M');
        $row_total = 0;
        //获取参数

        $notesnr = str_replace("\r\n", "\n", $_POST['notesnr']); //短信内容/不过滤

//        $dingshitime = trim(input('post.dingshitime')); //定时发送时间
//        $is_dingshi  = input('post.is_dingshi');
        $is_dingshi  =0;
        $file        = '';

        //号码
        $phonesarr = [];
        //渠道
        $cid = session('relate_id');

            //是否渠道账号
            if (session('user_type') != 'channel') {
                return json(['code' => 0, 'msg' => "提交错误：该账户不是渠道账号"]);
            }
            //是否绑定渠道
            if (empty(session('relate_id'))) {
                return json(['code' => 0, 'msg' => "提交错误：该账户没有绑定渠道"]);
            }
            //是否绑定渠道
            if (Channel::get(['channel_id' => session('relate_id'), 'status' => '0'])) {
                return json(['code' => 0, 'msg' => "提交错误：该账户渠道已禁用，请联系管理员"]);
            }


        /**
         * 号码以文件形式导入
         */
        if (input('post.txtflie')) {
//            // 获取表单上传文件
//            try {
//                $file = request()->file('phonesfile');
//            } catch (\Exception $e) {
//                trace($e->getMessage(), 'send');
//                if (session('username') == 'admin') {
//                    return json(['code' => 0, 'msg' => "提交错误" . $e->getMessage()]);
//                    exit;
//                }
//                return json(['code' => 0, 'msg' => "提交错误"]);
//
//            }
//            // 移动到框架应用根目录/public/uploads/sendnote 目录下'size'=>6*1024*1024,
//            if ($file) {
//                $info = $file->validate(['size' => 11 * 1024 * 1024, 'ext' => 'xlsx'])->move(Env::get('root_path') . 'public/uploads/sendnote');
//                if ($info) {
//
//                    $infos = $info->getInfo();
//                    // 成功上传后 获取上传信息
//                    $savename = Env::get('root_path') . 'public/uploads/sendnote/' . $info->getSaveName();
//                    //          $open = file_get_contents($savename);
//                    // $phonesarr = explode("\r\n",$open);
//                    trace('用户' . session('username') . '文件导入提交号码，保存在服务器的文件：' . $savename . '，原文件名：' . $infos['name'], 'send');
//                    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                    try {
//                        // 读取文件数量
//                        $config = ['path' => Env::get('root_path')];
//                        $excel  = new \Vtiful\Kernel\Excel($config);
//
//                        $excelData = $excel->openFile('public/uploads/sendnote/' . $info->getSaveName())->nextCellCallback(function ($row, $cell, $data) use (&$row_total) {
//                            if ($cell == 0 && !empty($data) && $data != 'XLSX_ROW_END' && $row != 0) {
//                                $row_total++;
//                            }
//                        });
//                        unset($excelData);
//                        unset($excel);
//                    } catch (\Exception $e) {
//                        trace('读取文件号码报错' . $e->getMessage(), 'error');
//                    }
//                    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                    //检查文件格式
//                    require_once Env::get('vendor_path') . 'PHPExcel/PHPExcel.php';
//
//                    $excelType   = \PHPExcel_IOFactory::identify($savename);
//                    $excelReader = \PHPExcel_IOFactory::createReader($excelType);
//
//                    $excelFilter           = new PHPExcelReadFilter();
//                    $excelFilter->startRow = 1; //只取第一第二行
//                    $excelFilter->endRow   = 2; //只取第一第二行
//                    $excelReader->setReadFilter($excelFilter);
//                    $phpexcel = $excelReader->load($savename);
//                    $sheet    = $phpexcel->getActiveSheet();
//
//                    $highestColumm = $sheet->getHighestColumn(); // 取得总列数
//
//                    for ($i = 'A'; $i <= $highestColumm; $i++) {
//                        // 1.列数检查，以每列第一个cell有没有填标题为准，必须每列都需要有标题
//                        if (empty($sheet->getCell($i . '1')->getValue())) {
//                            return json(['code' => 0, 'msg' => $i . "列的标题不能为空，如果是空列请删除"]);
//                        }
//
//                        // 2.每列的第一个cell的属性是不是常规
//                        if ($sheet->getStyle($i . '1')->getNumberFormat()->getFormatCode() != 'General') {
//                            return json(['code' => 0, 'msg' => $i . "1 单元格不是常规格式，请设置excel表格{$i}列的单元格格式为常规"]);
//                        }
//                        // 3.每列的第二个cell有没有填充内容(空格去掉)
//                        if (empty($sheet->getCell($i . '2')->getValue())) {
//                            return json(['code' => 0, 'msg' => "{$i}2单元格不能为空，如果该列不需要请删除"]);
//                        }
//                    }
//
//                } else {
//                    // 上传失败获取错误信息
//                    trace($file->getError());
//                    return json(['code' => 0, 'msg' => $file->getError()]);
//                }
//            } else {
//                return json(['code' => 0, 'msg' => "文件没有上传"]);
//            }
        } else {
            if ($is_dingshi == 1) {
                return json(['code' => 0, 'msg' => "定时请使用文件发送"]);
            }
            //手动输入号码阶段------------------------------
            /**
             * [$phones description]
             * @var [type]
             */
            $phones = trim(input('post.phones'));
            if (empty($phones)) {
                return json(['code' => 0, 'msg' => "提交错误：填写号码"]);
            }
            //号码转为数组
            $phonesarr = explode(',', $phones);
            trace('用户' . session('username') . '手动输入提交号码：' . $phones, 'send');
            if (count($phonesarr) > 4000) {
                return json(['code' => 0, 'msg' => "大量号码请使用文件发送"]);
            }
            //检查过后的合格的号码
            $phoneJC = [];
            foreach ($phonesarr as $key => $value) {
                $numhang = $key + 1;
                //去除两边的空格
                $valueone = trim($value);
                if (empty($valueone)) {
                    trace("提交错误：第{$numhang}个号码错误，空的", 'send');
                    continue;
                }

                $phoneJC[] = $valueone;
            }

            if (count($phoneJC) <= 0) {
                return json(['code' => 0, 'msg' => "请输入正确号码"]);
            }

            $sendData = $this->send_mians($phoneJC, $notesnr, $cid);

            if ($sendData['resultCode'] == 0) {
                return json(['code' => 200, 'msg' => "发送成功：发送订单号【" . $sendData['data']['msgId'] . "】"]);
            } else {
                return json(['code' => 0, 'msg' => "发送失败：" . $sendData['resultDesc']]);
            }

            return json(['code' => 0, 'msg' => "发送失败了，请联系管理员"]);

            //手动输入号码阶段------------------------------
        }

        // if(session('username') == 'admin')
        // {
        //     dump($_FILES['phonesfile']['size']);
        //     exit;
        // }

        // 数据全部校验后，判断是否定时任务
        if ($is_dingshi == 1) {

            if (!$file) {
                return json(['code' => 0, 'msg' => "定时请使用文件发送"]);
            }

            if (empty($dingshitime)) {
                return json(['code' => 0, 'msg' => "未设置定时发送时间"]);
                return;
            }

            $data = [
                // 'order_type'  => 2,
                // 'batch_num'   => uniqid() . rand(100,999),
                'channel_id'  => $cid,
                'username'    => session('username'),
                'send_time'   => $dingshitime,
                'create_time' => date('Y-m-d H:i:s', time()),
                // 'is_file'     => $is_file,
                'save_name'   => $savename,
                'message'     => input('post.message'),
                'sms_content' => $notesnr,
                'status'      => 0,
                'pull_total'  => $row_total,
                'sms_type'    => 3,
            ];

            $selfdom_info_id = db('bus_selfdom_info')->insertGetId($data);

            if ($selfdom_info_id) {
                $mqinsert       = new MqInsertService('sendtask', 'app\Job\SendNoteDo');
                $mqinsertReslut = $mqinsert->addJob(['id' => $selfdom_info_id]);

                trace("已加入定时任务:" . json_encode($data, JSON_UNESCAPED_SLASHES), 'send');

                return json(['code' => 200, 'msg' => "上传成功，已加入定时任务"]);
            }

            return json(['code' => 0, 'msg' => "已加入定时任务失败，请联系管理员"]);
        }

        //文件发送
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);

        $post_data = array(
            'file' => new \CURLFile(realpath($savename))
            , 'cid' => $cid
            , 'content' => $notesnr,
        );

        trace("上传数据" . json_encode($post_data, JSON_UNESCAPED_UNICODE), "send");

        curl_setopt($curl, CURLOPT_URL, 'http://119.91.61.33:8080/SMS/upload/qf');

        curl_setopt($curl, CURLOPT_POST, 1);

        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($curl, CURLOPT_USERAGENT, "TEST");

        $result = curl_exec($curl);

        trace("上传结果" . $result, "send");

        $error = curl_error($curl);

        $result = json_decode($result, true);

        //关闭URL请求
        curl_close($curl);

        if ($result['code'] == 200) {
            return json(['code' => 200, 'msg' => "发送成功，请在发送查询中查看最终结果"]);
        } else {
            trace("上传错误" . $error, "send");
            return json(['code' => 0, 'msg' => "发送失败"]);
        }

    }

    //免审接口
    public function send_mians($phonesarr, $notesnr, $cid)
    {
        //设置post数据
        $post_data = array(
            'channelOrderCode' => date('YmdHis') . uniqid() . rand(10, 99),
            'phoneList'        => $phonesarr,
            'channelId'        => $cid,
            'content'          => $notesnr,
            'sign'             => '1231231231',
        );

        trace('发送参数：' . json_encode($post_data, JSON_UNESCAPED_UNICODE), 'send');

        //获取key
//        $keym = Channelkey::get(['cid' => $cid]);
//        $key  = $keym['cid_key'];
//
//        //将号码数组转成字符串
//        $number = '[' . implode(',', $phonesarr) . ']';
//
//        //拼接签名
//        $tmp = "channelCallbackUrl={$post_data['channelCallbackUrl']}";
//        $tmp .= "&channelOrderId={$post_data['channelOrderId']}";
//        $tmp .= "&cid={$post_data['cid']}";
//        $tmp .= "&number={$number}";
//        // $tmp  .= "&operator={$post_data['operator']}";
//        $tmp .= "&key={$key}";

//        trace('加密参数：' . $tmp, 'send');

        //设置http头
        $header   = array();
//        $header[] = 'Authorization:' . md5($tmp);
        $header[] = 'Accept:application/json';
        $header[] = 'Content-Type:application/json;charset=utf-8';

        //初始化
        $curl = curl_init();
        //设置抓取的url
        $purl = 'http://47.83.207.50:8855/rsm/submit';
        trace('接口发送地址：' . $purl, 'send');
        curl_setopt($curl, CURLOPT_URL, $purl);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //设置头文件
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        //设置post数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post_data, JSON_UNESCAPED_SLASHES));
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        trace('用户' . session('username') . '发送短信接收的响应信息：' . $data, 'send');

        $data = json_decode($data, true);
        return $data;

    }

    /**
     * 注意事项
     * @Author   lf
     * @DateTime 2019-07-29T16:47:09+0800
     * @return   [type]                   [description]
     */
    public function attentiontxt()
    {
        $txt  = $_POST['atxt'];
        $type = input('post.type');

        if ($type == 1) {
            $type = '';
        }

        $txt = str_replace("\'", "'", $txt);
        $txt = str_replace('\"', '"', $txt);
        $txt = explode("\n", $txt);

        // foreach ($txt as $key => $value) {
        //     $txt[$key] = addslashes($value);
        // }

        if (session('user_type') == "admin") {
            cache("send_attentiontxt" . $type, $txt);
            return "设置完成";
        }

        return "失败";

    }

    public function postTxt()
    {
        $url       = 'http://47.83.207.50:8855/rsm/smsTextInfo';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        $c=str_replace("\r\n", "\n", $_POST['notesnr']);;
        curl_setopt($ch, CURLOPT_POSTFIELDS, $c);


        curl_setopt($ch, CURLOPT_HEADER, 0);
        //设置头部信息
        $headers = array('Content-Type: text/plain;');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        //执行请求
        $output = curl_exec($ch);
        //打印获得的数据
        curl_close($ch);
        $output = json_decode($output, 1);
        return json($output['data']);
    }
}

require_once Env::get('vendor_path') . 'PHPExcel/PHPExcel.php';
/**
 * 读取excel过滤器类 单独文件
 */
class PHPExcelReadFilter implements \PHPExcel_Reader_IReadFilter
{

    public $startRow = 1;
    public $endRow;

    public function readCell($column, $row, $worksheetName = '')
    {
        if (!$this->endRow) {
            return true;
        }

        if ($row >= $this->startRow && $row <= $this->endRow) {
            return true;
        }

        return false;
    }

}
